package utils

import (
	"io"
	"net/http"
	"net/url"
	"strings"

	"github.com/zeromicro/go-zero/core/logx"
)

func PostWww(host string, data any) (string, error) {
	return PostUrl(host, data, "application/x-www-form-urlencoded")
}

func PostJson(host string, data any) (string, error) {
	return PostUrl(host, data, "application/json")
}

func PostForm(host string, data map[string]string) (string, error) {
	values := url.Values{}
	for key, val := range data {
		values.Add(key, val)
	}

	resp, err := http.PostForm(host, values)
	if err != nil {
		logx.Errorf("POST-FORM接口请求失败,错误为：%v", err)
		return "", err
	}
	defer resp.Body.Close()
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		logx.Errorf("POST-FORM读取HTTP响应失败: %s，error: %v", host, err)
		return "", err
	}
	result := string(body)
	logx.Infof("POST-FORM接口请求结果为：%s", result)
	return result, nil
}

func PostUrl(url string, data any, contentType string) (string, error) {
	dataStr := StructToJson(data)
	logx.Infof("POST接口请求,参数为：%s", data)
	resp, err := http.Post(url, contentType, strings.NewReader(dataStr))
	if err != nil {
		logx.Errorf("POST接口请求失败,错误为：%v", err)
		return "", err
	}
	defer resp.Body.Close()
	logx.Info("POST接口请求成功", resp.Header.Get("Content-Type"))
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		logx.Errorf("POST读取HTTP响应失败: %s，error: %v", url, err)
		return "", err
	}
	result := string(body)
	logx.Infof("POST接口请求结果为：%s", result)
	return result, nil
}

func GetUrl(host string, data map[string]string) (string, error) {
	u, err := url.Parse(host)
	if err != nil {
		logx.Errorf("GET解析URL报错: %s，error: %v", host, err)
		return "", err
	}

	params := u.Query()
	for key, val := range data {
		params.Add(key, val)
	}
	u.RawQuery = params.Encode()

	resp, err := http.Get(u.String())
	if err != nil {
		logx.Errorf("GET接口请求失败,错误为：%v", err)
		return "", err
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		logx.Errorf("GET读取响应失败: %s，error: %v", u.String(), err)
		return "", err
	}
	result := string(body)
	logx.Infof("POST接口请求结果为：%s", result)
	return result, nil
}
